/**
 * Copyright (c) 2015 Baidu. All Rights Reserved.
 *
 * @file 用于Objective-C文件生成
 * @author yuanguozheng
 */
var template = require('art-template');
var moment = require('moment');
var config = require('../utils/config');
var fileutil = require('../utils/fileutil');
var path = require('path');

/**
 * 利用OC模板进行渲染
 *
 * @param {Object} data 传入的参数
 * @param {string} basePath 基本路径
 * @param project
 * @param pkgName
 * @param mapping
 * @param callback
 */
function render(data, basePath, project, pkgName, mapping, callback) {
    if (data == null) {
        return;
    }
    template.config('escape', false);
    template.config('extname', '.tmpl');
    template.config('base', path.join(__dirname, '../templates'));
    var year = moment().format('YYYY');
    var date = moment().format('YY/M/D');
    for (var i = 0; i < data.length; i++) {
        getSetter(data[i].member);
        var renderData = {
            project: project,
            data: data[i],
            year: year,
            date: date,
            mapping: mapping
        };
        var headerFile = template('oc_h', renderData);
        var implFile = template('oc_m', renderData);
        var realPath = path.join(basePath, project, pkgName);
        if (!fileutil.mkdir(realPath)) {
            return;
        }
        fileutil.writeToFile(realPath, renderData.data.cls + '.h', headerFile);
        fileutil.writeToFile(realPath, renderData.data.cls + '.m', implFile);
        if (i == data.length - 1) {
            callback();
        }
    }
}

/**
 * 设置属性的setter
 *
 * @param {Array} members 类的成员
 */
function getSetter(members) {
    var setters = config.setters();
    members.forEach(function (i) {
        var s = setters[i.type];
        if (s) {
            i.setter = s;
        } else {
            i.setter = 'strong';
        }
    });
}

module.exports = render;